/**
 * GroupFileParser.java 16.06.2006
 */
package org.dicr.sys.linux;

import java.io.*;
import java.util.*;
import java.util.logging.*;

import org.dicr.util.data.*;
import org.dicr.util.data.exc.*;

/**
 * System groups file parser.
 * 
 * @author <A href='http://dicr.org'>Igor A Tarasov</A>
 * @version 060616
 */
public class GroupFileParser {

	private static final Logger log = Logger.getLogger(GroupFileParser.class.getName());

	/**
	 * Parse groups file
	 * 
	 * @param in
	 *            input stream
	 * @return elementrs of parsed file
	 * @throws IOException
	 */
	public static Map<String, SysGroup> parse(Reader in) throws IOException {
		if (in == null) throw new IllegalArgumentException("null input");
		Map<String, SysGroup> sysGroups = new HashMap<>();
		BufferedReader reader = new BufferedReader(in);
		while (true) {
			String line = reader.readLine();
			if (line == null) break;
			line = StringUtils.normalize(line);
			if (line == null || line.startsWith("#")) continue;
			String[] fields = line.split(":", 4);
			try {
				if (fields.length < 3) throw new FileFormatException(line);
				String name = fields[0];
				int gid = Integer.parseInt(fields[2]);
				Collection<String> extraMembers = new ArrayList<>();
				if (fields.length > 3) {
					String[] memlist = fields[3].split(",");
					for (String member : memlist) {
						extraMembers.add(member);
					}
				}
				sysGroups.put(name, new SysGroup(name, gid, extraMembers));
			} catch (Exception fex) {
				log.log(Level.WARNING, "error parsing group file line: " + line, fex);
			}
		}
		reader.close();
		return sysGroups;
	}
}
